// 模拟产品数据
const products = [
    {
        id: 1,
        name: "智能手表 Pro",
        price: "¥1,299",
        description: "全新一代智能手表，支持心率监测、GPS定位、50米防水，续航长达7天。",
        image: "https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=400&h=300&fit=crop",
        category: "electronics"
    },
    {
        id: 2,
        name: "无线蓝牙耳机",
        price: "¥499",
        description: "主动降噪技术，高清音质，30小时超长续航，舒适佩戴体验。",
        image: "https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=400&h=300&fit=crop",
        category: "electronics"
    },
    {
        id: 3,
        name: "时尚运动鞋",
        price: "¥699",
        description: "透气网面设计，缓震鞋底，适合日常运动和休闲穿着。",
        image: "https://images.unsplash.com/photo-1542291026-7eec264c27ff?w=400&h=300&fit=crop",
        category: "clothing"
    },
    {
        id: 4,
        name: "极简台灯",
        price: "¥199",
        description: "北欧简约设计，三档亮度调节，护眼LED光源，USB充电。",
        image: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=300&fit=crop",
        category: "home"
    },
    {
        id: 5,
        name: "便携咖啡机",
        price: "¥899",
        description: "一键操作，15bar压力，可制作意式浓缩、美式咖啡，小巧便携。",
        image: "https://images.unsplash.com/photo-1517668808426-b7f4adc21237?w=400&h=300&fit=crop",
        category: "home"
    },
    {
        id: 6,
        name: "商务双肩包",
        price: "¥399",
        description: "大容量设计，防水面料，多功能分区，适合商务出行和日常使用。",
        image: "https://images.unsplash.com/photo-1553062407-98eeb64c6a62?w=400&h=300&fit=crop",
        category: "clothing"
    },
    {
        id: 7,
        name: "智能音箱",
        price: "¥599",
        description: "AI语音助手，360°环绕音效，支持智能家居控制，海量音乐资源。",
        image: "https://images.unsplash.com/photo-1558089687-f282ffcbc0d4?w=400&h=300&fit=crop",
        category: "electronics"
    },
    {
        id: 8,
        name: "香薰加湿器",
        price: "¥159",
        description: "超声波静音技术，七彩氛围灯，大容量水箱，持续加湿8小时。",
        image: "https://images.unsplash.com/photo-1584464491033-06628f3a6b7b?w=400&h=300&fit=crop",
        category: "home"
    },
    {
        id: 9,
        name: "运动T恤",
        price: "¥129",
        description: "速干面料，透气排汗，修身剪裁，多种颜色可选。",
        image: "https://images.unsplash.com/photo-1521572163474-6864f9cf17ab?w=400&h=300&fit=crop",
        category: "clothing"
    }
];

// 全局变量
let currentProducts = [...products];
let currentCategory = 'all';

// DOM元素
const productGrid = document.getElementById('productGrid');
const modal = document.getElementById('productModal');
const closeBtn = document.querySelector('.close');
const filterBtns = document.querySelectorAll('.filter-btn');

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    renderProducts(currentProducts);
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    // 筛选按钮事件
    filterBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            const category = e.target.dataset.category;
            filterProducts(category);
            
            // 更新活动按钮样式
            filterBtns.forEach(b => b.classList.remove('active'));
            e.target.classList.add('active');
        });
    });

    // 关闭模态框
    closeBtn.addEventListener('click', closeModal);
    window.addEventListener('click', (e) => {
        if (e.target === modal) {
            closeModal();
        }
    });

    // ESC键关闭模态框
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            closeModal();
        }
    });
}

// 渲染产品列表
function renderProducts(productsToRender) {
    productGrid.innerHTML = '';
    
    if (productsToRender.length === 0) {
        productGrid.innerHTML = '<p class="loading">没有找到相关产品</p>';
        return;
    }

    productsToRender.forEach(product => {
        const productCard = createProductCard(product);
        productGrid.appendChild(productCard);
    });
}

// 创建产品卡片
function createProductCard(product) {
    const card = document.createElement('div');
    card.className = 'product-card';
    card.innerHTML = `
        <img src="${product.image}" alt="${product.name}" class="product-image">
        <div class="product-info">
            <h3 class="product-title">${product.name}</h3>
            <p class="product-price">${product.price}</p>
            <p class="product-description">${product.description}</p>
            <span class="product-category">${getCategoryName(product.category)}</span>
        </div>
    `;

    // 添加点击事件
    card.addEventListener('click', () => showProductDetail(product));

    return card;
}

// 获取分类中文名
function getCategoryName(category) {
    const categoryMap = {
        'electronics': '电子产品',
        'clothing': '服装',
        'home': '家居'
    };
    return categoryMap[category] || category;
}

// 筛选产品
function filterProducts(category) {
    currentCategory = category;
    
    if (category === 'all') {
        currentProducts = [...products];
    } else {
        currentProducts = products.filter(product => product.category === category);
    }
    
    renderProducts(currentProducts);
}

// 显示产品详情
function showProductDetail(product) {
    document.getElementById('modalImage').src = product.image;
    document.getElementById('modalTitle').textContent = product.name;
    document.getElementById('modalPrice').textContent = product.price;
    document.getElementById('modalDescription').textContent = product.description;
    
    modal.style.display = 'block';
    document.body.style.overflow = 'hidden';
}

// 关闭模态框
function closeModal() {
    modal.style.display = 'none';
    document.body.style.overflow = 'auto';
}

// 搜索功能（可选）
function searchProducts(query) {
    const filtered = currentProducts.filter(product => 
        product.name.toLowerCase().includes(query.toLowerCase()) ||
        product.description.toLowerCase().includes(query.toLowerCase())
    );
    renderProducts(filtered);
}

// 添加搜索框（可选功能）
function addSearchBox() {
    const searchContainer = document.createElement('div');
    searchContainer.className = 'search-container';
    searchContainer.innerHTML = `
        <input type="text" id="searchInput" placeholder="搜索产品..." class="search-input">
        <button onclick="clearSearch()" class="clear-btn">清除</button>
    `;
    
    const filterBar = document.querySelector('.filter-bar');
    filterBar.parentNode.insertBefore(searchContainer, filterBar.nextSibling);
    
    const searchInput = document.getElementById('searchInput');
    searchInput.addEventListener('input', (e) => {
        searchProducts(e.target.value);
    });
}

// 清除搜索
function clearSearch() {
    document.getElementById('searchInput').value = '';
    renderProducts(currentProducts);
}

// 添加搜索框样式
const searchStyles = `
    .search-container {
        text-align: center;
        margin-bottom: 2rem;
    }
    
    .search-input {
        padding: 0.75rem 1.5rem;
        border: 2px solid #ddd;
        border-radius: 25px;
        width: 300px;
        max-width: 100%;
        font-size: 1rem;
        transition: border-color 0.3s ease;
    }
    
    .search-input:focus {
        outline: none;
        border-color: #667eea;
    }
    
    .clear-btn {
        margin-left: 1rem;
        padding: 0.75rem 1.5rem;
        background: #f8f9fa;
        border: 1px solid #ddd;
        border-radius: 25px;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    
    .clear-btn:hover {
        background: #e9ecef;
    }
`;

// 动态添加搜索框样式
const styleSheet = document.createElement('style');
styleSheet.textContent = searchStyles;
document.head.appendChild(styleSheet);

// 页面加载完成后添加搜索框
document.addEventListener('DOMContentLoaded', () => {
    addSearchBox();
});

// 平滑滚动效果
function smoothScrollToTop() {
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}

// 添加回到顶部按钮
function addBackToTopButton() {
    const backToTopBtn = document.createElement('button');
    backToTopBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
    backToTopBtn.className = 'back-to-top';
    backToTopBtn.style.cssText = `
        position: fixed;
        bottom: 2rem;
        right: 2rem;
        background: #667eea;
        color: white;
        border: none;
        border-radius: 50%;
        width: 50px;
        height: 50px;
        cursor: pointer;
        display: none;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        transition: all 0.3s ease;
        z-index: 1000;
    `;
    
    document.body.appendChild(backToTopBtn);
    
    window.addEventListener('scroll', () => {
        if (window.pageYOffset > 300) {
            backToTopBtn.style.display = 'block';
        } else {
            backToTopBtn.style.display = 'none';
        }
    });
    
    backToTopBtn.addEventListener('click', smoothScrollToTop);
}

// 添加回到顶部按钮
document.addEventListener('DOMContentLoaded', () => {
    addBackToTopButton();
});
